package com.efounder.chat.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.provider.MediaStore;
import androidx.viewpager.widget.ViewPager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.core.xml.StubObject;
import com.efounder.chat.R;
//import com.efounder.chat.activity.BaiduMapActivity;
import com.efounder.chat.activity.RecorderActivity;
import com.efounder.chat.adapter.ChatVoicePlayClickListener;
import com.efounder.chat.adapter.ExpressionAdapter;
import com.efounder.chat.adapter.ExpressionPagerAdapter;
import com.efounder.chat.fragment.ChatOfficialAccountsSenderFragment.OnOfficialAccountKyeboardClickListener;
import com.efounder.chat.listener.OnTouchListViewListener;
import com.efounder.chat.manager.ChatMenuManager;
import com.efounder.chat.model.ChatMenuModel;
import com.efounder.chat.struct.MessageChildTypeConstant;
import com.efounder.chat.struct.StructFactory;
import com.efounder.chat.utils.FileSizeUtil;
import com.efounder.chat.utils.FileUtil;
import com.efounder.chat.utils.ImageUtil;
import com.efounder.chat.utils.MessagePanSoftUtils;
import com.efounder.chat.utils.SmileUtils;
import com.efounder.chat.utils.VoiceRecorder;
import com.efounder.chat.view.ChatEditText;
import com.efounder.chat.widget.ExpandGridView;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.EFFragment;
import com.efounder.imageselector.activity.MultiImageSelectorActivity;
import com.efounder.imageselector.utils.FileUtils;
import com.efounder.message.struct.IMStruct002;
import com.efounder.util.AbFragmentManager;
import com.efounder.util.ToastUtil;
import com.efounder.utils.CommonUtils;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.UriUtils;

import java.io.File;
import java.io.FileInputStream;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.concurrent.Executors;

/**
 * 聊天发送器fragment
 *
 * @author hudq
 */
public class ChatSenderFragment extends EFFragment implements OnClickListener,
        OnTouchListViewListener, ChatMenuManager.OnMenuClickListener {
    public static final String TAG = "PublicChatSenderFragment";

    public static final String COPY_IMAGE = "EASEMOBIMG";
    public static final int REQUEST_CODE_CAMERA = 18;
    private static final int REQUEST_IMAGE = 2;
    private static final int REQUEST_CODE_SELECT_VIDEO = 200;

    private static final int REQUEST_CODE_MAP = 4;// 位置
    private static final int REQUEST_CODE_FILE = 6;//文件
    // private static final int REQUEST_WEB_URL = 5;// 获取网址，发送网址消息

    // 发送图片时默认的图片压缩保存路径
    public static String chatpath = ImageUtil.chatpath;

    private Context mContext;
    private OnVoiceRecordListener onVoiceRecordListener;
    private OnClickMessageEditTextListener onClickMessageEditTextListener;
    private SendMessageCallback sendMessageCallback;
    private PreSendMessageCallback preSendMessageCallback;
    private OnTouchListViewListener onTouchListViewListener;

    /** 语音容器（语音时显示在中间的麦克风容器） **/
    // private View recordingContainer;
    /** 麦克风图片 **/
    // private ImageView micImage;
    /** 语音时 “手指上滑，取消发送” 提示 **/
    // private TextView recordingHint;
    /** 麦克风动画资源文件,用于录制语音时 **/
    // private Drawable[] micImages;
    /** 聊天ListView **/
    // private ChatListView chatListView;
    /** 聊天ListView 的 adapter **/
    // private PublicChatAdapter chatAdapter;
    // private List<MessageBean> messageBeans;
    /**
     * 消息输入框
     **/
    private ChatEditText mEditTextContent;
    /**
     * 键盘按钮
     **/
    private View buttonSetModeKeyboard;
    /**
     * 语音按钮
     **/
    private View buttonSetModeVoice;
    /**
     * 发送按钮
     **/
    private View buttonSend;
    /**
     * 按住说话 按钮
     **/
    private View buttonPressToSpeak;
    /**
     * 表情图片 容器
     **/
    private LinearLayout emoticonContainer;
    /**
     * 图片，表情，名片等按钮 容器
     **/
    private LinearLayout btnContainer;
    /**
     * 点击更多按钮显示的View
     **/
    private View more;
    /**
     * 剪切板
     **/
    private ClipboardManager clipboard;
    /**
     * 表情ViewPager
     **/
    private ViewPager expressionViewpager;
    /**
     * 菜单ViewPager  图片 小视频
     **/
    private ViewPager menuViewpager;
    /**
     * 每页表情图标数量
     **/
    private final int expressionPagesize = 20;
    private InputMethodManager manager;
    private int oldPosition = 0;// 记录上一次点的位置
    private int currentItem; // 当前页面

    private int oldMenuPoint = 0;// 菜单
    private int currentMenuPoint; // 菜单
    private ArrayList<View> dots;
    private ArrayList<View> menuPoints;
    /**
     * 表情资源list
     **/
    private List<String> emoticonReslist;
    /**
     * 菜单List
     **/
    private List<ChatMenuModel> menuReslist;

    private byte chatType;

    private VoiceRecorder voiceRecorder;
    private File cameraFile;
    public static int resendPos;

    /**
     * 表情图标-常态
     **/
    private ImageView iv_emoticons_normal;
    /**
     * 表情图标-选中
     **/
    private ImageView iv_emoticons_checked;
    private RelativeLayout edittext_layout;
    /** 下拉加载更多（转圈圈） **/
    // private ProgressBar loadmorePB;
    // private boolean isloading;
    // private boolean haveMoreData = true;
    /**
     * 更多按钮（右侧加号 ）
     **/
    private Button btnMore;
    public String playMsgId;
    /**
     * 拍照按钮
     **/
    private ImageView attach_cameraPhoto;
    /**
     * 新增图片按钮
     **/
    private ImageView attach_photo;
    /**
     * 视频
     **/
    private ImageView attach_video;
    /**
     * 名片
     **/
    private ImageView attach_visitingCard;
    /**
     * 消费凭证
     **/
    private ImageView attach_voucher;
    /**
     * 应用任务
     **/
    private ImageView attach_applicationask;
    /**
     * 阅后即焚
     **/
    private ImageView attach_burnAfterReading;
    /**
     * 位置
     **/
    private ImageView attach_location;

    String myUserNick = "";
    String myUserAvatar = "";
    String toUserNick = "";
    String toUserAvatar = "";
    // 分享的照片
    String iamge_path = null;
    // 从图库选择的照片
    private ArrayList<String> mSelectPath;
    // 视频path
    String video_path = null;
    // 设置按钮
    private ImageView iv_setting;
    private ImageView iv_setting_group;

    private PowerManager.WakeLock wakeLock;

    /**
     * 麦克风动画handler,用于录制语音时
     **/
    private Handler micImageHandler = new MyHandler(this);

    private View view;

    private int id;
    private ChatMenuManager chatMenuManager;

    private OnOfficialAccountKyeboardClickListener OnOfficialAccountKyeboardClickListener;
    private AbFragmentManager abFragmentManager;
    /**
     * 公众号键盘
     **/
    private ImageView iv_official_account_keyboard;
    private String currentChatPermission = "";


    static class MyHandler extends Handler {
        WeakReference<ChatSenderFragment> mFragment;

        MyHandler(ChatSenderFragment fragment) {
            mFragment = new WeakReference<ChatSenderFragment>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            ChatSenderFragment theFragment = mFragment.get();
            // 切换msg切换图片
            if (theFragment.onVoiceRecordListener != null) {
                theFragment.onVoiceRecordListener.onRecording(msg.what);
            }
        }
    }

    @Override
    public void onAttach(Activity context) {
        super.onAttach(context);
        this.mContext = context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.i("--", TAG + "onCreateView-------------");
        id = getActivity().getIntent().getIntExtra("id", 1);
        // 获取聊天类型，单聊、群聊，公众号
        chatType = getActivity().getIntent().getByteExtra("chattype",
                StructFactory.TO_USER_TYPE_PERSONAL);
        if (chatType == StructFactory.TO_USER_TYPE_PERSONAL || chatType == StructFactory.TO_USER_TYPE_OFFICIAL_ACCOUNT) {

        } else if (chatType == StructFactory.TO_USER_TYPE_GROUP) {


        }
        chatMenuManager = new ChatMenuManager(mContext);
        chatMenuManager.setOnMenuClickListener(this);
        abFragmentManager = new AbFragmentManager(getActivity());
        view = inflater
                .inflate(R.layout.fragment_chat_sender, container, false);

        initView();
        setupView();

        return view;
    }

    /**
     * initView
     */
    protected void initView() {
        // recordingContainer = view.findViewById(R.id.recording_container);
        // micImage = (ImageView) view.findViewById(R.id.mic_image);
        // recordingHint = (TextView) view.findViewById(R.id.recording_hint);
        // chatListView = (ChatListView) view.findViewById(R.id.list);
        iv_official_account_keyboard = (ImageView) view
                .findViewById(R.id.iv_official_account_keyboard);
        iv_official_account_keyboard.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (OnOfficialAccountKyeboardClickListener != null) {
                    OnOfficialAccountKyeboardClickListener
                            .onOfficialAccountKyeboardClick(v, true);
                }
            }
        });

//        attach_cameraPhoto = (ImageView) view
//                .findViewById(R.id.btn_take_picture);
//        attach_cameraPhoto.setOnClickListener(this);
//        attach_photo = (ImageView) view.findViewById(R.id.btn_picture);
//        attach_photo.setOnClickListener(this);
//        attach_video = (ImageView) view.findViewById(R.id.btn_video);
//        attach_video.setOnClickListener(this);
//        attach_visitingCard = (ImageView) view
//                .findViewById(R.id.btn_visiting_card);
//        attach_visitingCard.setOnClickListener(this);
//        attach_voucher = (ImageView) view.findViewById(R.id.btn_vouchers);
//        attach_voucher.setOnClickListener(this);
//        attach_applicationask = (ImageView) view
//                .findViewById(R.id.btn_application_task);
//        attach_applicationask.setOnClickListener(this);
//        attach_burnAfterReading = (ImageView) view
//                .findViewById(R.id.btn_burn_after_reading);
//        attach_burnAfterReading.setOnClickListener(this);
//        attach_location = (ImageView) view.findViewById(R.id.btn_location);
//        attach_location.setOnClickListener(this);
//
        mEditTextContent = (ChatEditText) view.findViewById(R.id.et_sendmessage);
        mEditTextContent.setOnClickListener(this);
        //TODO  输入@选择群成员
//        mEditTextContent.setOnMentionInputListener(new ChatEditText.OnMentionInputListener() {
//            @Override
//            public void onMentionCharacterInput() {
//                //跳转到@界面
//                Intent intent = new Intent(getContext(), SelectGroupUserActivity.class);
//                intent.putExtra("title", "选择群聊成员");
//                intent.putExtra("id", id);
//                startActivityForResult(intent, 0);
//            }
//        });

        buttonSetModeKeyboard = view.findViewById(R.id.btn_set_mode_keyboard);
        buttonSetModeKeyboard.setOnClickListener(this);
        edittext_layout = (RelativeLayout) view
                .findViewById(R.id.edittext_layout);
        buttonSetModeVoice = view.findViewById(R.id.btn_set_mode_voice);
        buttonSetModeVoice.setOnClickListener(this);
        buttonSend = view.findViewById(R.id.btn_send);
        buttonSend.setOnClickListener(this);
        buttonPressToSpeak = view.findViewById(R.id.btn_press_to_speak);

        expressionViewpager = (ViewPager) view.findViewById(R.id.vPager);
        menuViewpager = (ViewPager) view.findViewById(R.id.menuadater);
        emoticonContainer = (LinearLayout) view
                .findViewById(R.id.ll_face_container);
        btnContainer = (LinearLayout) view.findViewById(R.id.ll_btn_container);
        iv_emoticons_normal = (ImageView) view
                .findViewById(R.id.iv_emoticons_normal);
        iv_emoticons_checked = (ImageView) view
                .findViewById(R.id.iv_emoticons_checked);
        // loadmorePB = (ProgressBar) view.findViewById(R.id.pb_load_more);
        btnMore = (Button) view.findViewById(R.id.btn_more);
        btnMore.setOnClickListener(this);
        iv_emoticons_normal.setVisibility(View.VISIBLE);
        iv_emoticons_checked.setVisibility(View.INVISIBLE);
        more = view.findViewById(R.id.more);
        /**输入框内容显示为保存的草稿内容**/
        mEditTextContent.setText(EnvironmentVariable.getProperty(id + "" + chatType));
        /**如果存在草稿，则用发送按钮替换更多按钮**/
        if (!mEditTextContent.getText().toString().equals("")) {
            buttonSend.setVisibility(View.VISIBLE);
            btnMore.setVisibility(View.GONE);
        }
        // edittext_layout.setBackgroundResource(R.drawable.input_bar_bg_normal);

        // 动画资源文件,用于录制语音时
        // micImages = new Drawable[] {
        // getResources().getDrawable(R.drawable.record_animate_01),
        // getResources().getDrawable(R.drawable.record_animate_02),
        // getResources().getDrawable(R.drawable.record_animate_03),
        // getResources().getDrawable(R.drawable.record_animate_04),
        // getResources().getDrawable(R.drawable.record_animate_05),
        // getResources().getDrawable(R.drawable.record_animate_06),
        // getResources().getDrawable(R.drawable.record_animate_07),
        // getResources().getDrawable(R.drawable.record_animate_08),
        // getResources().getDrawable(R.drawable.record_animate_09),
        // getResources().getDrawable(R.drawable.record_animate_10),
        // getResources().getDrawable(R.drawable.record_animate_11),
        // getResources().getDrawable(R.drawable.record_animate_12),
        // getResources().getDrawable(R.drawable.record_animate_13),
        // getResources().getDrawable(R.drawable.record_animate_14), };

        // 表情list
        emoticonReslist = getExpressionRes(87);
        // 初始化表情viewpager
        List<View> views = new ArrayList<View>();
        View gv1 = getGridChildView(1);
        View gv2 = getGridChildView(2);
        View gv3 = getGridChildView(3);
        View gv4 = getGridChildView(4);
        View gv5 = getGridChildView(5);
        views.add(gv1);
        views.add(gv2);
        views.add(gv3);
        views.add(gv4);
        views.add(gv5);
        dots = new ArrayList<View>();
        dots.add(view.findViewById(R.id.dot_1));
        dots.add(view.findViewById(R.id.dot_2));
        dots.add(view.findViewById(R.id.dot_3));
        dots.add(view.findViewById(R.id.dot_4));
        dots.add(view.findViewById(R.id.dot_5));
        menuPoints = new ArrayList<View>();
        menuPoints.add(view.findViewById(R.id.menu_point_1));
        menuPoints.add(view.findViewById(R.id.menu_point_2));
        menuPoints.add(view.findViewById(R.id.menu_point_3));
        menuPoints.add(view.findViewById(R.id.menu_point_4));


        expressionViewpager.setAdapter(new ExpressionPagerAdapter(views));

        expressionViewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                dots.get(oldPosition).setBackgroundResource(
                        R.drawable.dot_normal);
                dots.get(position)
                        .setBackgroundResource(R.drawable.dot_focused);

                oldPosition = position;
                currentItem = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        // initMenu();
        edittext_layout.requestFocus();
        voiceRecorder = new VoiceRecorder(micImageHandler);
        buttonPressToSpeak.setOnTouchListener(new PressToSpeakListen());
        mEditTextContent.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    more.setVisibility(View.GONE);
                    iv_emoticons_normal.setVisibility(View.VISIBLE);
                    iv_emoticons_checked.setVisibility(View.INVISIBLE);
                    emoticonContainer.setVisibility(View.GONE);
                    btnContainer.setVisibility(View.GONE);
//                    edittext_layout
//                            .setBackgroundResource(R.drawable.input_bar_bg_active);
                } else {
//                    edittext_layout
//                            .setBackgroundResource(R.drawable.input_bar_bg_normal);
                }

            }
        });
        mEditTextContent.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
//                edittext_layout
//                        .setBackgroundResource(R.drawable.input_bar_bg_active);
                more.setVisibility(View.GONE);
                iv_emoticons_normal.setVisibility(View.VISIBLE);
                iv_emoticons_checked.setVisibility(View.INVISIBLE);
                emoticonContainer.setVisibility(View.GONE);
                btnContainer.setVisibility(View.GONE);
            }
        });
        // 监听文字框
        mEditTextContent.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (!TextUtils.isEmpty(s)) {
                    btnMore.setVisibility(View.GONE);
                    buttonSend.setVisibility(View.VISIBLE);
                } else {
                    btnMore.setVisibility(View.VISIBLE);
                    buttonSend.setVisibility(View.GONE);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

    //初始化下方的菜单
    private void initMenu() {
        List<View> views = chatMenuManager.getGridViews(id, chatType, currentChatPermission);
        for (int i = 0; i < views.size(); i++) {
            menuPoints.get(i).setVisibility(View.VISIBLE);
        }
        if (views.size() == 1) {
            menuPoints.get(0).setVisibility(View.GONE);
        }
        menuViewpager.setAdapter(new ExpressionPagerAdapter(views));

        menuViewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                menuPoints.get(oldMenuPoint).setBackgroundResource(
                        R.drawable.dot_normal);
                menuPoints.get(position)
                        .setBackgroundResource(R.drawable.dot_focused);

                oldMenuPoint = position;
                currentMenuPoint = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    @SuppressWarnings("deprecation")
    private void setupView() {
        // activityInstance = this;
        iv_emoticons_normal.setOnClickListener(this);
        iv_emoticons_checked.setOnClickListener(this);
        clipboard = (ClipboardManager) getActivity().getSystemService(
                Context.CLIPBOARD_SERVICE);
        manager = (InputMethodManager) getActivity().getSystemService(
                Context.INPUT_METHOD_SERVICE);
        getActivity().getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        wakeLock = ((PowerManager) getActivity().getSystemService(
                Context.POWER_SERVICE)).newWakeLock(
                PowerManager.SCREEN_DIM_WAKE_LOCK, "demo");
        // wakeLock = ((PowerManager)
        // getActivity().getSystemService(Context.POWER_SERVICE)).newWakeLock(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
        // "demo");

        if (chatType == StructFactory.TO_USER_TYPE_OFFICIAL_ACCOUNT) {// 公众号

            ImageView iv_official_account_keyboard = (ImageView) view
                    .findViewById(R.id.iv_official_account_keyboard);
            iv_official_account_keyboard.setVisibility(View.VISIBLE);
        }
        // 给 chatList设置 adapter，并关联数据
        // messageBeans = new ArrayList<MessageBean>();
        // chatAdapter = new PublicChatAdapter(this, messageBeans);
        // chatListView.setAdapter(chatAdapter);
    }

    /**
     * 获取表情资源
     *
     * @param getSum
     * @return
     */
    public List<String> getExpressionRes(int getSum) {
        List<String> emoticonReslist = new ArrayList<String>();
        for (int x = 1; x <= getSum; x++) {

            String filename = "ee_" + x;
            emoticonReslist.add(filename);
        }
        return emoticonReslist;
    }

    /**
     * 获取表情gridview
     *
     * @param i
     * @return
     */
    private View getGridChildView(int i) {
        View view = View.inflate(getActivity(), R.layout.expression_gridview,
                null);
        ExpandGridView gv = (ExpandGridView) view.findViewById(R.id.gridview);
        List<String> list = new ArrayList<String>();
        if (i == 1) {
            List<String> list1 = emoticonReslist.subList(0, expressionPagesize);
            list.addAll(list1);
        } else if (i == 2) {
            // list.addAll(emoticonReslist.subList(expressionPagesize,
            // emoticonReslist.size()));
            List<String> list2 = emoticonReslist
                    .subList(expressionPagesize, 40);
            list.addAll(list2);
        } else if (i == 3) {
            List<String> list3 = emoticonReslist.subList(40, 60);
            list.addAll(list3);

        } else if (i == 4) {
            List<String> list4 = emoticonReslist.subList(60, 80);
            list.addAll(list4);
        } else if (i == 5) {
            list.addAll(emoticonReslist.subList(80, emoticonReslist.size()));
        }
        list.add("delete_expression");
        final ExpressionAdapter expressionAdapter = new ExpressionAdapter(
                getActivity(), 1, list);
        gv.setAdapter(expressionAdapter);
        gv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                String filename = expressionAdapter.getItem(position);
                try {
                    // 文字输入框可见时，才可输入表情
                    // 按住说话可见，不让输入表情
                    if (buttonSetModeKeyboard.getVisibility() != View.VISIBLE) {
                        if (filename != "delete_expression") { // 不是删除键，显示表情
                            // 这里用的反射，所以混淆的时候不要混淆SmileUtils这个类
                            @SuppressWarnings("rawtypes")
                            Class clz = Class
                                    .forName("com.efounder.chat.utils.SmileUtils");
                            Field field = clz.getField(filename);
                            mEditTextContent.append(SmileUtils.getSmiledText(
                                    getActivity(), (String) field.get(null)));
                        } else { // 删除文字或者表情
                            if (!TextUtils.isEmpty(mEditTextContent.getText())) {
                                int selectionStart = mEditTextContent
                                        .getSelectionStart();// 获取光标的位置
                                if (selectionStart > 0) {
                                    String body = mEditTextContent.getText()
                                            .toString();
                                    String tempStr = body.substring(0,
                                            selectionStart);
                                    int i = tempStr.lastIndexOf("[");// 获取最后一个表情的位置
                                    if (i != -1) {
                                        CharSequence cs = tempStr.substring(i,
                                                selectionStart);
                                        if (SmileUtils.containsKey(cs
                                                .toString()))
                                            mEditTextContent.getEditableText()
                                                    .delete(i, selectionStart);
                                        else
                                            mEditTextContent.getEditableText()
                                                    .delete(selectionStart - 1,
                                                            selectionStart);
                                    } else {
                                        mEditTextContent.getEditableText()
                                                .delete(selectionStart - 1,
                                                        selectionStart);
                                    }
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
        return view;
    }


    /**
     * 按住说话listener
     */
    class PressToSpeakListen implements View.OnTouchListener {
        @SuppressLint({"ClickableViewAccessibility", "Wakelock"})
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    if (!CommonUtils.isExitsSdcard()) {
                        Toast.makeText(getActivity(), R.string.wechatview_send_voice_need_sdcard,
                                Toast.LENGTH_SHORT).show();
                        return false;
                    }
                    try {
                        v.setPressed(true);
                        wakeLock.acquire();
                        if (ChatVoicePlayClickListener.isPlaying)
                            ChatVoicePlayClickListener.currentPlayListener
                                    .stopPlayVoice();
                        voiceRecorder.startRecording(null, id
                                + "", getActivity());
                        if (onVoiceRecordListener != null) {
                            onVoiceRecordListener.onRecorderButtonTouchDown(v);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        v.setPressed(false);
                        if (wakeLock.isHeld())
                            wakeLock.release();
                        if (voiceRecorder != null)
                            voiceRecorder.discardRecording();
                        Toast.makeText(getActivity(), R.string.recoding_fail,
                                Toast.LENGTH_SHORT).show();
                        return false;
                    }

                    return true;
                case MotionEvent.ACTION_MOVE: {
                    if (onVoiceRecordListener != null) {
                        boolean isCancleRecord;
                        if (event.getY() < 0) {
                            isCancleRecord = true;
                        } else {
                            isCancleRecord = false;
                        }
                        onVoiceRecordListener.onRecorderButtonTouchMove(v,
                                isCancleRecord);
                    }
                    return true;
                }
                case MotionEvent.ACTION_UP:
                    v.setPressed(false);
                    if (onVoiceRecordListener != null) {
                        onVoiceRecordListener.onRecorderButtonTouchUp(v);
                    }
                    if (wakeLock.isHeld())
                        wakeLock.release();
                    if (event.getY() < 0) {
                        // discard the recorded audio.
                        voiceRecorder.discardRecording();
                    } else {
                        // stop recording and send voice file
                        try {
                            int length = voiceRecorder.stopRecoding();
                            if (length > 0) {
                                if (sendMessageCallback != null) {
                                    MessagePanSoftUtils.sendMsg(voiceRecorder.getVoiceFilePath(), length + "", preSendMessageCallback, MessageChildTypeConstant.subtype_voice, chatType);
//								IMStruct002 struct002 = StructFactory
//										.getInstance()
//										.createVoiceStruct(
//												voiceRecorder
//														.getVoiceFilePath(),
//												voiceRecorder
//														.getVoiceFileName(id
//																+ ""),
//												Integer.toString(length), false);
//								sendMessageCallback.sendMessage(struct002);
                                }
                                // sendMessageCallback.sendVoice(voiceRecorder.getVoiceFilePath(),
                                // voiceRecorder.getVoiceFileName(toChatUsername),
                                // Integer.toString(length), false);
                            }
//                            else if (length == EMError.INVALID_FILE) {
//                                Toast.makeText(getActivity(), "无录音权限",
//                                        Toast.LENGTH_SHORT).show();
//                            }
                            else {
                                Toast.makeText(getActivity(), R.string.wechatview_record_time_short,
                                        Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(getActivity(), R.string.wechatview_send_fail_please_check,
                                    Toast.LENGTH_SHORT).show();
                        }

                    }
                    return true;
                default:
                    if (onVoiceRecordListener != null) {
                        onVoiceRecordListener.onRecorderButtonTouchCancle(v);
                    }
                    if (voiceRecorder != null)
                        voiceRecorder.discardRecording();
                    return false;
            }
        }
    }

    /**
     * 点击文字输入框
     *
     * @param v
     */
    public void editClick(View v) {
        if (onClickMessageEditTextListener != null) {
            onClickMessageEditTextListener.onClickMessageEditText(v);
        }
        if (more.getVisibility() == View.VISIBLE) {
            more.setVisibility(View.GONE);
            iv_emoticons_normal.setVisibility(View.VISIBLE);
            iv_emoticons_checked.setVisibility(View.INVISIBLE);
        }

    }

    /**
     * 返回
     *
     * @param view
     */
    // public void back(View view) {
    // finish();
    // }

    /**
     * 显示语音图标按钮
     *
     * @param view
     */
    public void setModeVoice(View view) {
        hideKeyboard();
        edittext_layout.setVisibility(View.GONE);
        more.setVisibility(View.GONE);
        view.setVisibility(View.GONE);
        buttonSetModeKeyboard.setVisibility(View.VISIBLE);
        buttonSend.setVisibility(View.GONE);
        btnMore.setVisibility(View.VISIBLE);
        buttonPressToSpeak.setVisibility(View.VISIBLE);
        iv_emoticons_normal.setVisibility(View.VISIBLE);
        iv_emoticons_checked.setVisibility(View.INVISIBLE);
        btnContainer.setVisibility(View.VISIBLE);
        emoticonContainer.setVisibility(View.GONE);

    }

    /**
     * 隐藏软键盘
     */
    private void hideKeyboard() {
        if (getActivity().getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getActivity().getCurrentFocus() != null)
                manager.hideSoftInputFromWindow(getActivity().getCurrentFocus()
                        .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 显示键盘图标
     *
     * @param view
     */
    public void setModeKeyboard(View view) {
        edittext_layout.setVisibility(View.VISIBLE);
        more.setVisibility(View.GONE);
        view.setVisibility(View.GONE);
        buttonSetModeVoice.setVisibility(View.VISIBLE);
        // mEditTextContent.setVisibility(View.VISIBLE);
        mEditTextContent.requestFocus();
        // buttonSend.setVisibility(View.VISIBLE);
        buttonPressToSpeak.setVisibility(View.GONE);
        if (TextUtils.isEmpty(mEditTextContent.getText())) {
            btnMore.setVisibility(View.VISIBLE);
            buttonSend.setVisibility(View.GONE);
        } else {
            btnMore.setVisibility(View.GONE);
            buttonSend.setVisibility(View.VISIBLE);
        }

    }

    /**
     * 显示或隐藏图标按钮页(点击右侧加号按钮)
     *
     * @param view
     */
    public void more(View view) {
        if (more.getVisibility() == View.GONE) {
            initMenu();
            hideKeyboard();
            more.postDelayed(new Runnable() {
                @Override
                public void run() {
                    more.setVisibility(View.VISIBLE);
                    btnContainer.setVisibility(View.VISIBLE);
                    emoticonContainer.setVisibility(View.GONE);
                }
            }, 250);

        } else {
            if (emoticonContainer.getVisibility() == View.VISIBLE) {
                emoticonContainer.setVisibility(View.GONE);
                btnContainer.setVisibility(View.VISIBLE);
                iv_emoticons_normal.setVisibility(View.VISIBLE);
                iv_emoticons_checked.setVisibility(View.INVISIBLE);
            } else {
                more.setVisibility(View.GONE);
            }

        }
    }


    //菜单点击
    @Override
    public void onMenuItemClick(ChatMenuModel model) {
        int type = model.getType();
        if (type == ChatMenuModel.TAKEPIC) {
            selectPicFromCamera();// 点击照相图标
        } else if (type == ChatMenuModel.PICTURE) {
            selectPicFromLocal(); // 点击图片图标
        } else if (type == ChatMenuModel.LOCATION) { // 位置
//            startActivityForResult(
//                    new Intent(mContext, BaiduMapActivity.class),
//                    REQUEST_CODE_MAP);
        } else if (type == ChatMenuModel.MINGPIAN) { // 名片
            sendText("\\3");
        } else if (type == ChatMenuModel.VOUCHERS) { // 消费凭证
            //sendText("\\4");
            sendText("\\56");
        } else if (type == ChatMenuModel.ALLPICATION_TASK) { // 应用任务
            //sendText("\\5");
            sendText("\\57");
        } else if (type == ChatMenuModel.VEDIO) {
            // 点击摄像图标
            Intent intent = new Intent(getActivity(), RecorderActivity.class);
            startActivityForResult(intent, REQUEST_CODE_SELECT_VIDEO);
        } else if (type == ChatMenuModel.COMMON) {//通用页面item
            try {
                //todo 处理弹出动画
                StubObject stubObject = model.getStubObject();
                Hashtable<String, String> hashtable = stubObject.getStubTable();
                //默认的进入activity或者fragment的动画
                int inTransition = R.anim.slide_in_from_right;
                int outTransition = R.anim.slide_out_to_left;
                if (hashtable.containsKey("tcms")) {
                    String tcms = hashtable.get("tcms");
                    if (!tcms.equals("") && tcms.equals("present")) {
                        //由下向上弹出
                        inTransition = R.anim.push_bottom_in;
                        outTransition = R.anim.push_top_out;
                    }
                }
                hashtable.put("toUserId", String.valueOf(id));
                hashtable.put("chatType", String.valueOf(chatType));

                stubObject.setStubTable(hashtable);

                //todo 跳转页面
                Bundle bundle = new Bundle();
                bundle.putSerializable("stubObject", stubObject);
                abFragmentManager.startActivity(model.getStubObject(), inTransition, outTransition);

            } catch (Exception e) {
                e.printStackTrace();
            }


        } else if (type == ChatMenuModel.FILE) {
            // 成功
//            video_path = data.getStringExtra("path");
//            String videoTime = data.getStringExtra("videoTime");

            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            startActivityForResult(intent, REQUEST_CODE_FILE);

        }

    }

    /**
     * 消息图标点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {

        int id = view.getId();
        if (id == R.id.btn_send) {// 点击发送按钮(发文字和表情)
            String s = mEditTextContent.getText().toString();
            sendText(s);
        }

//        else if (id == R.id.btn_take_picture) {
//            selectPicFromCamera();// 点击照相图标
//        } else if (id == R.id.btn_picture) {
//            selectPicFromLocal(); // 点击图片图标
//        } else if (id == R.id.btn_location) { // 位置
//            startActivityForResult(
//                    new Intent(mContext, BaiduMapActivity.class),
//                    REQUEST_CODE_MAP);
//        } else if (id == R.id.btn_visiting_card) { // 名片
//            sendText("\\3");
//        } else if (id == R.id.btn_vouchers) { // 消费凭证
//            //sendText("\\4");
//            sendText("\\56");
//        } else if (id == R.id.btn_application_task) { // 应用任务
//            //sendText("\\5");
//            sendText("\\57");
//        } else if (id == R.id.btn_burn_after_reading) { // 应用任务
//            sendText("\\9");
//        }

        else if (id == R.id.iv_emoticons_normal) { // 点击显示表情框

            hideKeyboard();
            iv_emoticons_normal.postDelayed(new Runnable() {
                @Override
                public void run() {
                    emoticonContainer.setVisibility(View.VISIBLE);
                    more.setVisibility(View.VISIBLE);
                    iv_emoticons_normal.setVisibility(View.INVISIBLE);
                    iv_emoticons_checked.setVisibility(View.VISIBLE);
                    btnContainer.setVisibility(View.GONE);
                }
            }, 250);
        } else if (id == R.id.iv_emoticons_checked) { // 点击隐藏表情框
            iv_emoticons_normal.setVisibility(View.VISIBLE);
            iv_emoticons_checked.setVisibility(View.INVISIBLE);
            btnContainer.setVisibility(View.VISIBLE);
            emoticonContainer.setVisibility(View.GONE);
            more.setVisibility(View.GONE);

        }
//        else if (id == R.id.btn_video) {
//            // 点击摄像图标
//            Intent intent = new Intent(getActivity(), RecorderActivity.class);
//            startActivityForResult(intent, REQUEST_CODE_SELECT_VIDEO);
//        }
//        else if (id == R.id.btn_file) { // 点击文件图标
//            // selectFileFromLocal();
//        } else if (id == R.id.btn_voice_call) { // 点击语音电话图标
//            if (!EMChatManager.getInstance().isConnected()) {
//                Toast.makeText(getActivity(), "尚未连接至服务器，请稍后重试",
//                        Toast.LENGTH_SHORT).show();
//            } else {
//                // startActivity(new Intent(getActivity(),
//                // VoiceCallActivity.class).putExtra("username",
//                // toChatUsername).putExtra("isComingCall", false));
//            }
//        }
        // TODO
        else if (id == R.id.btn_set_mode_voice) {// 左侧语音按钮
            setModeVoice(view);
        } else if (id == R.id.btn_set_mode_keyboard) {// 左侧键盘按钮
            setModeKeyboard(view);
        } else if (id == R.id.et_sendmessage) {// 消息输入框
            editClick(view);
        } else if (id == R.id.btn_more) {// 更多按钮（右侧加号 ）
            more(view);
        }
    }

    /**
     * 发送文本消息
     *
     * @param content message content
     *                boolean resend
     */
    private void sendText(String content) {

        if (content.trim().length() > 0) {
            if (sendMessageCallback != null) {
                IMStruct002 struct002 = StructFactory.getInstance().createTextStruct(content, chatType);
                sendMessageCallback.sendMessage(struct002);
            }
            mEditTextContent.setText("");
        }
    }

    /**
     * 录音监听
     *
     * @author hudq
     */
    public interface OnVoiceRecordListener {
        /**
         * 录音按钮按下
         **/
        public void onRecorderButtonTouchDown(View v);

        /**
         * 录音按钮移动
         *
         * @param v
         * @param isCancleRecord 是否取消录音
         */
        public void onRecorderButtonTouchMove(View v, boolean isCancleRecord);

        /**
         * 录音按钮弹起
         **/
        public void onRecorderButtonTouchUp(View v);

        /**
         * 录音按钮取消（默认行为）
         **/
        public void onRecorderButtonTouchCancle(View v);

        /**
         * 正在录音
         *
         * @param musicalScale 音阶
         */
        public void onRecording(int musicalScale);
    }

    /**
     * 点击消息输入框监听
     *
     * @author hudq
     */
    public interface OnClickMessageEditTextListener {
        public void onClickMessageEditText(View v);
    }

    public interface SendMessageCallback {

        public void sendMessage(IMStruct002 struct002);

    }

    public void setOnVoiceRecordListener(
            OnVoiceRecordListener onVoiceRecordListener) {
        this.onVoiceRecordListener = onVoiceRecordListener;
    }

    public void setOnClickMessageEditTextListener(
            OnClickMessageEditTextListener onClickMessageEditTextListener) {
        this.onClickMessageEditTextListener = onClickMessageEditTextListener;
    }

    public void setSendMessageCallback(SendMessageCallback sendMessageCallback) {
        this.sendMessageCallback = sendMessageCallback;
    }

    public void setOnOfficialAccountKyeboardClickListener(
            OnOfficialAccountKyeboardClickListener onOfficialAccountKyeboardClickListener) {
        OnOfficialAccountKyeboardClickListener = onOfficialAccountKyeboardClickListener;
    }

    /**
     * 照相获取图片
     */
    public void selectPicFromCamera() {
        if (!CommonUtils.isExitsSdcard()) {
            Toast.makeText(getActivity(), R.string.wechatview_no_have_sdcard, Toast.LENGTH_SHORT)
                    .show();
            return;
        }

        /*
         * cameraFile = new File(Environment.getExternalStorageDirectory(),
         *
         * System.currentTimeMillis() + ".jpg");
         * cameraFile.getParentFile().mkdirs(); startActivityForResult( new
         * Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(
         * MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)),
         * REQUEST_CODE_CAMERA);
         */

        cameraFile = FileUtils.createTmpFile(getActivity());
        // 跳转到系统照相机
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (cameraIntent.resolveActivity(getActivity().getPackageManager()) != null) {
            // 设置系统相机拍照后的输出路径

            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                    UriUtils.getUriForFile(cameraFile));
            startActivityForResult(cameraIntent, REQUEST_CODE_CAMERA);
            getActivity().sendBroadcast(
                    new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri
                            .fromFile(cameraFile)));// 刷新系统相册
        } else {
            Toast.makeText(getActivity(), R.string.msg_no_camera,
                    Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 从图库获取图片
     */
    public void selectPicFromLocal() {

        Intent intent = new Intent(getActivity(),
                MultiImageSelectorActivity.class);
        // 是否显示拍摄图片
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
        // 最大可选择图片数量
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 9);
        // 选择模式
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE,
                MultiImageSelectorActivity.MODE_MULTI);
        // 默认选择
        // if (mSelectPath != null && mSelectPath.size() > 0) {
        // intent.putExtra(
        // MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST,
        // mSelectPath);
        // }

        // XXX yqs
        startActivityForResult(intent, REQUEST_IMAGE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i("--", TAG + "-----------requestCode:" + requestCode
                + ",resultCode" + resultCode);
        if (resultCode == Activity.RESULT_OK) {
            // 相机拍摄的照片
            if (requestCode == REQUEST_CODE_CAMERA) {
                if (cameraFile != null && cameraFile.exists()) {
                    System.out.println(cameraFile.getAbsolutePath());
                    String scale = ImageUtil.saveNewImage(cameraFile.getAbsolutePath(), 1280,
                            1280);
                    if (sendMessageCallback != null) {
                        MessagePanSoftUtils.sendMsg(chatpath + ImageUtil.getFileName(chatpath + cameraFile.getName()) + ".pic", scale, preSendMessageCallback, MessageChildTypeConstant.subtype_image, chatType);
                    }
                }
            }
            // 从图库选择的照片
            else if (requestCode == REQUEST_IMAGE) {
                Log.d("wwl_request_received", requestCode + "");
                mSelectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                new AsyncTask<String, Integer, String>() {
                    ProgressDialog progressDialog = new ProgressDialog(getActivity());

                    @Override
                    protected void onPreExecute() {
                        super.onPreExecute();
                        progressDialog.setMessage(ResStringUtil.getString(R.string.common_text_please_wait));
                        progressDialog.show();
                    }

                    @Override
                    protected String doInBackground(String... params) {
                        for (int i = 0; i < mSelectPath.size(); i++) {
                            System.out.println(mSelectPath.get(i));
                            //如果不是gif动图则进行裁剪压缩
                            if (!ImageUtil.isGifFile((new File(mSelectPath.get(i))))) {
                                ImageUtil.saveNewImage(mSelectPath.get(i), 1280, 1280);
                            }
                            Log.i("--", TAG + chatpath + ImageUtil.getFileName(mSelectPath.get(i)));
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(String s) {
                        super.onPostExecute(s);
                        if (progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        for (int i = 0; i < mSelectPath.size(); i++) {
                            if (!ImageUtil.isGifFile((new File(mSelectPath.get(i))))) {
                                String scale = ImageUtil.getPicScale(chatpath + ImageUtil.getFileName(mSelectPath.get(i)) + ".pic");
                                if (sendMessageCallback != null) {
                                    MessagePanSoftUtils.sendMsg(chatpath + ImageUtil.getFileName(mSelectPath.get(i)) + ".pic", scale, preSendMessageCallback, MessageChildTypeConstant.subtype_image, chatType);
//                        MessagePanSoftUtils.sendMsg(mSelectPath.get(i), scale, preSendMessageCallback, MessageChildTypeConstant.subtype_image,chatType);

                                }
                            } else {
                                String scale = ImageUtil.getPicScale(mSelectPath.get(i));
                                if (sendMessageCallback != null) {
                                    MessagePanSoftUtils.sendMsg(mSelectPath.get(i), scale, preSendMessageCallback, MessageChildTypeConstant.subtype_image, chatType);
                                }
                            }
                        }
                    }
                }.executeOnExecutor(Executors.newCachedThreadPool());
//                new Thread(neww Runnable() {
//                    @Override
//                    public void run() {
//
//                    }
//                }).start();

            } else if (requestCode == REQUEST_CODE_SELECT_VIDEO) {
                // 成功
                video_path = data.getStringExtra("path");
                String videoTime = data.getStringExtra("videoTime");
                double fileSize = FileSizeUtil.getFileOrFilesSize(video_path, FileSizeUtil.SIZETYPE_KB);
                if (fileSize < 20) {
                    //视频过小，录制失败，不发送消息
                    ToastUtil.showToast(getActivity(), R.string.wechatview_video_record_fail);
                    return;
                }
                if (sendMessageCallback != null) {
                    MessagePanSoftUtils.sendMsg(video_path, videoTime, preSendMessageCallback, MessageChildTypeConstant.subtype_smallVideo, chatType);
                }
                /*
                 * // 通过路径获取第一帧的缩略图并显示 Bitmap bitmap =
                 * ImageUtil.createVideoThumbnail(video_path); BitmapDrawable
                 * drawable = new BitmapDrawable(bitmap);
                 * drawable.setTileModeXY(Shader.TileMode.REPEAT,
                 * Shader.TileMode.REPEAT); drawable.setDither(true);
                 */
                // btnPlay.setBackgroundDrawable(drawable);
            } else if (requestCode == REQUEST_CODE_MAP) {
                // 地图
                /** 当前地图图片位置 */
                String curGSONInfo = data.getStringExtra("curGSONInfo");
//				PublicMessagePanSoftUtils.sendMsg(curGSONInfo, sendMessageCallback, MessageChildTypeConstant.subtype_location);
                IMStruct002 struct002 = StructFactory.getInstance()
                        .createMapStruct(curGSONInfo, chatType);
                sendMessageCallback.sendMessage(struct002);
            } else if (requestCode == REQUEST_CODE_FILE && resultCode == Activity.RESULT_OK) {
                //文件
                File file;
                String filePath;
                Uri fileUri = data.getData();
                try {
                    filePath = FileUtil.getPathByUri4kitkat(mContext, fileUri);
                    if (sendMessageCallback != null) {
                        File file2 = new File(filePath);
                        String autoFileOrFilesSize = FileSizeUtil.getAutoFileOrFilesSize(filePath);
                        if (file2.exists()) {
                            FileInputStream fis = null;
                            try {
                                fis = new FileInputStream(file2);
                                MessagePanSoftUtils.sendMsg(filePath, autoFileOrFilesSize, preSendMessageCallback, MessageChildTypeConstant.subtype_file, chatType);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                // 失败
            }
        }
        //@选择群成员列表
//        if (requestCode == 0 && resultCode == 1) {
//            User selectUser = (User) data.getSerializableExtra("selectUser");
//            String selectUserName = selectUser.getNickName();
//            int selectId = selectUser.getId();
//            mEditTextContent.addSpan(selectUserName, selectId);
//            mEditTextContent.append(" ");
//        }

    }

    @Override
    public void onPause() {
        super.onPause();
        if (wakeLock.isHeld())
            wakeLock.release();
        if (ChatVoicePlayClickListener.isPlaying
                && ChatVoicePlayClickListener.currentPlayListener != null) {
            // 停止语音播放
            ChatVoicePlayClickListener.currentPlayListener.stopPlayVoice();
        }

        try {
            // 停止录音
            if (voiceRecorder.isRecording()) {
                voiceRecorder.discardRecording();
                // recordingContainer.setVisibility(View.INVISIBLE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onTouchListView() {
        if (emoticonContainer.getVisibility() == View.VISIBLE) {
            iv_emoticons_normal.setVisibility(View.VISIBLE);
            iv_emoticons_checked.setVisibility(View.GONE);
        }
        more.setVisibility(View.GONE);
    }


    public interface PreSendMessageCallback {

        public void preSendMessage(IMStruct002 struct002);

        public void updateProgress(IMStruct002 struct002, double percent);

        public void sendPreMessage(IMStruct002 struct002);

    }

    public PreSendMessageCallback getPreSendMessageCallback() {
        return preSendMessageCallback;
    }

    public void setPreSendMessageCallback(PreSendMessageCallback preSendMessageCallback) {
        this.preSendMessageCallback = preSendMessageCallback;
    }

    public void setOnTouchListViewListener(OnTouchListViewListener onTouchListViewListener) {
        this.onTouchListViewListener = onTouchListViewListener;
    }

    /**
     * 方便activity将权限传递过来
     *
     * @param chatPermission
     */
    public void setchatPermission(String chatPermission) {
        currentChatPermission = chatPermission;
    }
}
